<template>
  <div class="app-container">
    <div
      v-show="
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !purchOrderCheckApplicationInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearTypeFlag"
          :slipSelectRequest="slipSelectRequestFlag"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList"> </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :check-box="false"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>
    <!-- 明细 -->
    <purch-application-summary-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :tableRow="detailInfo.data"
      @returnBack="getList"
    />
    <purch-order-check-application
      v-if="purchOrderCheckApplicationInfo.visible"
      v-model:visible="purchOrderCheckApplicationInfo.visible"
      :purchApplicationId="purchOrderCheckApplicationInfo.orderId"
      :purch-application-info="purchOrderCheckApplicationInfo.info"
      :purch-type="purchOrderCheckApplicationInfo.purchType"
      :purch-according="purchOrderCheckApplicationInfo.purchAccording"
      :title="purchOrderCheckApplicationInfo.title"
      @returnModify="returnModify"
    />
    <select-order
      v-if="showSelectOrder"
      v-model:show-dialog="showSelectOrder"
      :query="showSelectOrderQuery"
      @callback="callbackOrder"
    ></select-order>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <page-dialog
      v-if="pageDialogInfo.visible"
      :title="pageDialogInfo.title"
      v-model:visible="pageDialogInfo.visible"
      :width="pageDialogInfo.width"
      :bt-loading="pageDialogInfo.btLoading"
      :bt-list="pageDialogInfo.btList"
      @reset="closeDialog"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="pageFormInfo.ref"
        :data="pageFormInfo.data"
        :field-list="pageFormInfo.fieldList"
        :label-width="pageFormInfo.labelWidth"
      />
    </page-dialog>
  </div>
</template>

<script setup name="applicationSummary">
import {
  getApplicationSummaryOrderPage,
  applicationSummaryOrderSubmit,
  applicationSummaryOrderDelete,
  applicationSummaryOrderRevoke,
  applicationSummaryOrderReject,
  applicationSummaryOrderRatifyt,
  applicationSummaryStop,
  applicationsSummaryValidatePurch,
} from '@/api/purch.js'
import { getReceiveAddressAll } from '@/api/core.js'
import PurchApplicationSummaryDetail from './detail'
import DetailList from './detailList'
import PurchOrderCheckApplication from '@/views/purch/order/checkPurchApplication.vue'
import SelectOrder from './selectOrder'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('applicationSummary:add'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '140',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('applicationSummary:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: deleteOrder,
        show: proxy.$permission('applicationSummary:delete'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: revokeOrder,
        show: proxy.$permission('applicationSummary:revoke'),
        ifRender: function (row) {
          let type = false
          if (row.status === 2) {
            type = true
          } else if (row.status === 3) {
            if (row.beforeMergeStatus === 3) {
              type = true
            } else {
              type = false
            }
          }
          return type
        },
      },
      {
        label: '批准',
        event: audit,
        show: proxy.$permission('applicationSummary:audit'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('applicationSummary:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '中止',
        event: checkBreak,
        show: proxy.$permission('applicationSummary:stop'),
        ifRender: function (row) {
          let type = false
          if (row.status === 5) {
            type = true
          } else if (row.status === 3) {
            if (row.beforeMergeStatus === 2 || row.beforeMergeStatus === 13) {
              type = true
            } else {
              type = false
            }
          }
          return type
        },
      },
      {
        label: '生成采购单',
        event: generatePurchOrder,
        show: proxy.$permission('applicationSummary:createPurchOrder'),
        ifRender: function (row) {
          return row.status === 5 || row.status === 3
        },
      },
    ],
  },
})
//明细相关
const detailInfo = reactive({
  visible: false,
  title: '申购单明细',
})
const purchOrderCheckApplicationInfo = reactive({
  visible: false,
  title: '通过申购汇总单生成采购单',
  orderId: null,
  purchType: 1,
  info: undefined,
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const pageDialogInfo = reactive({
  title: '选择采购依据',
  visible: false,
  type: '',
  width: '400px',
  row: {},
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeDialog,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveDialog,
      saveLoading: false,
      show: true,
    },
  ],
})
const pageFormInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '采购依据',
      value: 'purch_according',
      type: 'select-model',
      code: 'purch_according',
    },
  ],
})
const clearTypeFlag = ref(true)
const slipSelectRequestFlag = ref(true)
const showSelectOrder = ref(false)
const showSelectOrderQuery = ref({})
const selectRow = ref({})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
// watch(
//   () => toPage.value,
//   (val) => {
//     if (val) {
//       let menus = proxy.$store.state.permission.defaultMenus
//       menus.forEach((item) => {
//         if (item.children) {
//           item.children.forEach((el) => {
//             if (el.code === 'applicationSummary' && el.url === val.url) {
//               detailListInfo.visible = false
//               advancedSearchInfo.visible = false
//               preferenceInfo.visible = false
//               detailInfo.visible = false
//               purchOrderCheckApplicationInfo.visible = false
//               if (val.urlType === 1) {
//                 getList()
//               } else if (val.urlType === 2) {
//                 detailInfo.visible = true
//                 let data = {
//                   id: val.businessId,
//                 }
//                 detailInfo.data = data
//                 sessionStorage.setItem('storeRowId', val.businessId)
//               }
//               proxy.$store.dispatch('settings/toPage', '')
//             }
//           })
//         }
//       })
//     }
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// )

const obj = reactive({
  beforeMergeStatusValue: {
    label: '合并前状态值',
    value: 'beforeMergeStatusValue',
    asValue: 'beforeMergeStatus',
    componentType: 'select-model',
    code: 'purch_application_status',
    show: false,
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'purch_application_summary_status',
    show: false,
    hidden: true,
  },
})
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})

function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (purchOrderCheckApplicationInfo.purchApplicationId) {
    getList()
  } else {
    search()
  }
}
function setPreferenceCallback(obj) {
  slipSelectRequestFlag.value = !slipSelectRequestFlag.value
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  await getList()
  clearTypeFlag.value = !clearTypeFlag.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  proxy.$nextTick(() => {
    tableInfo.refresh = Math.random()
  })
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function close() {
  dialogInfo.visible = false
  formInfo.data = {}
}
function clearSearch() {
  clearTypeFlag.value = !clearTypeFlag.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.visible = true
  detailInfo.data = { ...row }
}
//提交
function submit(row) {
  applicationSummaryOrderSubmit([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//终止
function checkBreak(row) {
  applicationSummaryStop([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function closeDialog() {
  pageDialogInfo.visible = false
  pageFormInfo.data = {}
}
//生成采购单
function generatePurchOrder(row) {
  if (
    proxy.$store.state.permission.systemConfig.purch_according != '1' &&
    proxy.$store.state.permission.systemConfig.purch_according != '2'
  ) {
    pageDialogInfo.visible = true
    selectRow.value = row
  } else {
    const params = {
      isDefault: '1',
    }
    const validateApi = applicationsSummaryValidatePurch
    validateApi(row).then((resp) => {
      if (resp && resp.success) {
        getReceiveAddressAll(params).then((resp) => {
          if (resp && resp.success) {
            sessionStorage.setItem('storeRowId', row.id)
            purchOrderCheckApplicationInfo.visible = true
            purchOrderCheckApplicationInfo.orderId = row.id
            purchOrderCheckApplicationInfo.info = row
            purchOrderCheckApplicationInfo.purchAccording =
              proxy.$store.state.permission.systemConfig.purch_according
          }
        })
      }
    })
    return
  }
}
function saveDialog() {
  if (pageFormInfo.data.purch_according) {
    const params = {
      isDefault: '1',
    }
    const validateApi = applicationsSummaryValidatePurch
    validateApi(selectRow.value).then((resp) => {
      if (resp && resp.success) {
        getReceiveAddressAll(params).then((resp) => {
          if (resp && resp.success) {
            sessionStorage.setItem('storeRowId', selectRow.value.id)
            purchOrderCheckApplicationInfo.orderId = selectRow.value.id
            purchOrderCheckApplicationInfo.info = selectRow.value
            purchOrderCheckApplicationInfo.purchAccording =
              pageFormInfo.data.purch_according
            closeDialog()
            proxy.$nextTick(() => {
              purchOrderCheckApplicationInfo.visible = true
            })
          }
        })
      }
    })
    return
  } else {
    proxy.$message.warning('请选择采购依据')
  }
}
//删除
function deleteOrder(row) {
  applicationSummaryOrderDelete([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
function revokeOrder(row) {
  applicationSummaryOrderRevoke([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
//驳回
function reject(row) {
  proxy
    .$prompt('请输入驳回理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    .then(({ value }) => {
      const data = {
        id: row.id,
        rejectReason: value,
      }
      applicationSummaryOrderReject(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function audit(row) {
  //批准
  applicationSummaryOrderRatifyt([row.id]).then((res) => {
    if (res && res.success) {
      getList()
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
// 创建
function create() {
  showSelectOrder.value = true
}
function callbackOrder() {
  getList()
}
function getCustomize() {
  let param = {
    tableKey:
      'purchApplicationSummaryOrderNo-com.slip.spd.entity.vo.purch.PurchApplicationSummaryVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      tableInfo.api = getApplicationSummaryOrderPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
getCustomize()
</script>

<style scoped></style>
